<template>
  <div class="app-container">
    <el-row justify="space-around" type="flex">
      <el-col :span="12">
        <el-input v-model="filterText" placeholder="输入关键字进行过滤" />
        <!-- 左边显示权限树 -->
        <el-tree
          ref="treeRef"
          :data="treeData"
          :default-expanded-keys="expendedKeys"
          :filter-node-method="handleFilterNodeMethod"
          :props="defaultProps"
          class="permission-tree"
          highlight-current
          node-key="id"
          @node-click="handleNodeClick"
          @node-expand="handleNodeExpand"
          @node-collapse="handleNodeCollapse"
        />
      </el-col>
      <el-col :span="12">
        <!-- 右边显示新增修改表单 -->
        <el-form
          ref="addDataForm"
          :model="addDataForm"
          :rules="rules"
          label-position="right"
          label-width="120px"
          size="small"
          style="width: 400px;margin-top: 40px;"
        >
          <el-form-item label="父节点：" prop="parentName">
            <el-input v-model="addDataForm.parentName" placeholder="请先选中父节点" readonly />
          </el-form-item>
          <el-form-item label="权限名称：" prop="name">
            <el-input v-model="addDataForm.name" placeholder="权限名称" />
          </el-form-item>
          <el-form-item label="权限路径：" prop="path">
            <el-input v-model="addDataForm.path" placeholder="权限路径" />
          </el-form-item>
          <el-form-item label="备注：" prop="remark">
            <el-input v-model="addDataForm.remark" placeholder="备注信息" type="textarea" />
          </el-form-item>
          <el-form-item>
            <el-button v-permission="['/sys/permission/add']" size="small" type="primary" @click="handleAdd">新增
            </el-button>
            <el-button size="small" @click="resetDataForm">重置</el-button>
          </el-form-item>
        </el-form>
        <el-form
          ref="updateDataForm"
          :model="updateDataForm"
          :rules="rules"
          label-position="right"
          label-width="120px"
          size="small"
          style="width: 400px;margin-top: 40px;"
        >
          <el-form-item hidden prop="id">
            <el-input v-model="updateDataForm.id" placeholder="权限名称" />
          </el-form-item>
          <el-form-item label="权限名称：" prop="name">
            <el-input v-model="updateDataForm.name" placeholder="权限名称" />
          </el-form-item>
          <el-form-item label="权限路径：" prop="path">
            <el-input v-model="updateDataForm.path" placeholder="权限路径" />
          </el-form-item>
          <el-form-item label="备注：" prop="remark">
            <el-input v-model="updateDataForm.remark" placeholder="备注信息" type="textarea" />
          </el-form-item>
          <el-form-item>
            <el-button v-permission="['/sys/permission/update']" size="small" type="primary" @click="handleUpdate">修改
            </el-button>
            <el-button v-permission="['/sys/permission/delete']" size="small" type="danger" @click="handleDelete">删除
            </el-button>
            <el-button v-permission="['/sys/permission/search']" size="small" @click="resetDataForm">重置</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import { add, del, fetchTreeData, update } from '@/api/system/permission'

export default {
  name: 'Permission',
  data() {
    return {
      filterText: '',
      addDataForm: {
        parentId: '',
        parentName: '',
        name: '',
        path: '',
        remark: ''
      },
      updateDataForm: {
        id: '',
        parentId: '',
        name: '',
        path: '',
        remark: ''
      },
      rules: {
        name: [
          { required: true, message: '权限名称不能为空', trigger: 'change' }
        ],
        path: [
          { required: true, message: '权限路径不能为空', trigger: 'change' }
        ],
        parentName: [
          { required: true, message: '请先选中父节点', trigger: 'change' }
        ]
      },
      expendedKeys: [], // 记住打开的节点
      treeData: [],
      currentNode: null, // 当前树节点
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    }
  },
  watch: {
    filterText(val) {
      this.$refs.treeRef.filter(val)
    }
  },
  mounted() {
    this.getTreeData()
  },
  methods: {
    getTreeData() {
      fetchTreeData().then(res => {
        console.log(res)
        this.treeData = res.data
      })
    },
    handleAdd() {
      this.$refs['addDataForm'].validate(valid => {
        if (valid) {
          add(this.addDataForm)
            .then(res => {
              console.log(res)
              this.$message.success(res.msg || '修改权限成功')
              this.resetDataForm()
              this.getTreeData()
            })
            .catch(err => {
              console.log(err)
            })
        }
      })
    },
    handleUpdate() {
      this.$refs['updateDataForm'].validate(valid => {
        if (valid) {
          update(this.updateDataForm)
            .then(res => {
              console.log(res)
              this.$message.success(res.msg || '修改权限成功')
              this.resetDataForm()
              this.getTreeData()
            })
            .catch(err => {
              console.log(err)
            })
        }
      })
    },
    handleDelete() {
      // 需要判断当前删除的节点是否是页子节点，不是页子节点不允许删除
      if (this.currentNode && this.currentNode.children && this.currentNode.children.length > 0) {
        this.$message.warning('请选择页子节点进行删除操作')
        return false
      }
      if (this.updateDataForm.id) {
        this.$confirm('是否删除该权限？', '删除提示', { type: 'warning' })
          .then(() => {
            del(this.updateDataForm.id)
              .then(res => {
                console.log(res)
                this.$message.success(res.msg || '权限删除成功')
                this.resetDataForm()
                this.getTreeData()
              })
              .catch(err => {
                console.log(err)
              })
          })
          .catch(cancel => {
            console.log(cancel)
          })
      } else {
        this.$message.warning('请先选中你要删除的权限')
      }
    },
    resetDataForm() {
      this.$refs['addDataForm'].resetFields()
      this.$refs['updateDataForm'].resetFields()
    },
    handleNodeClick(data, node, item) {
      console.log(data)
      this.currentNode = data
      this.addDataForm.parentId = data.id
      this.addDataForm.parentName = data.name
      this.addDataForm.path = data.path
      this.updateDataForm.id = data.id
      this.updateDataForm.name = data.name
      this.updateDataForm.path = data.path
      this.updateDataForm.remark = data.remark
    },
    handleNodeExpand(data, node, item) {
      // 记录该节点已打开
      this.expendedKeys.push(data.id)
    },
    handleNodeCollapse(data, node, item) {
      // 把该节点从已打开状态列表中删除
      for (var i = 0; i < this.expendedKeys.length; i++) {
        if (this.expendedKeys[i] === data.id) {
          this.expendedKeys.splice(i, 1)
          break
        }
      }
    },
    handleFilterNodeMethod(value, data, node) {
      return data.name.indexOf(value) > -1
    }
  }
}
</script>
<style scoped>
.permission-tree {
  margin-top: 20px;
}
</style>
